<!--
 * @title:
 * @Description:
 * @Author: JZT.饶慧勇
 * @Date: 2025-05-27 18:53:05
 * @LastEditors: JZT.饶慧勇
 * @LastEditTime: 2025-06-11 08:56:30
-->
<script setup lang="ts">
import QQMapWX from 'qqmap-wx-jssdk';

import config from '@/config';

const userStore = useUserStore();

const uploadRef = ref();
const fileList1 = ref([]);

function handleChange({ fileList }) {
  console.log('fileList', fileList);
  fileList1.value = fileList;
}

function handleSuccess({ file, fileList, formData }) {
  console.log('file', file);
  console.log('fileList', fileList);
  console.log('formData', formData);
}

function onUploadClick() {
  uploadRef.value?.submit();
}

// 初始化（需要申请key）
let qqmapsdk: undefined | typeof QQMapWX = void 0;
const toast = useToast();
const { sendAuthorize } = useAuthorize();
const locationInfo = ref<null | {
  address: string;
  ad_info: { location: { lat: number; lng: number } };
}>(null);
const locationAddress = computed(() => {
  if (!locationInfo.value) return '';

  return `${locationInfo.value.ad_info.location.lat},${locationInfo.value.ad_info.location.lng}：${locationInfo.value.address}`;
});

function getLocation() {
  sendAuthorize('scope.userLocation', {
    showModalTitle: '需要位置权限',
    showModalMsg: '请授权位置信息以使用该功能',
    success() {
      uni.chooseLocation({
        success: res => {
          console.log('位置名称', res);
        },
        fail() {
          console.log('openSetting fail');
        }
      });
    }
  });
}

function searchHandle() {
  qqmapsdk?.search({
    keyword: '医院',
    success(res) {
      toast.show('搜索成功');
      console.log(res);
    },
    fail() {
      toast.show('搜索失败');
    }
  });
}

function getLocationAuto() {
  sendAuthorize('scope.userLocation', {
    showModalTitle: '需要位置权限',
    showModalMsg: '请授权位置信息以使用该功能',
    success() {
      uni.getLocation({
        type: 'gcj02', // 腾讯地图使用的坐标系
        success: res => {
          console.log(res);
          qqmapsdk?.reverseGeocoder({
            location: `${res.latitude},${res.longitude}`,
            success(res) {
              console.log(res);
              locationInfo.value = res.status === 0 ? res.result : null;
              toast.show('获取位置成功');
            },
            fail: err => {
              console.error('获取位置失败:', err);
              toast.show('获取位置失败');
            }
          });
        },
        fail: err => {
          console.error('获取位置失败:', err);
          toast.show('获取位置失败');
        }
      });
    }
  });
}

function openLocation() {
  sendAuthorize('scope.userLocation', {
    showModalTitle: '需要位置权限',
    showModalMsg: '请授权位置信息以使用该功能',
    success() {
      uni.openLocation({
        latitude: 30.555732,
        longitude: 114.219335,
        name: '邻家小厨(墨水湖北路店)',
        address: '湖北省武汉市汉阳区琴断口街道墨水湖北路十里铺472号(金色世家大门旁)'
      });
    }
  });
}

function addLocation() {
  uni.navigateTo({ url: 'plugin://address-form/index' });
}
function editLocation() {
  const info: EditInfo = {
    phone: '13397240336',
    receiver: '饶慧勇',
    default: true
  };
  uni.navigateTo({
    url: `plugin://address-form/index?edit=${JSON.stringify(info)}`
  });
}

function join(url: string) {
  uni.navigateTo({ url });
}

onLoad(() => {
  qqmapsdk = new QQMapWX({
    key: config.qqMapKey
  });
});

onUnload(() => {
  qqmapsdk = null;
});
</script>

<template>
  <view class="content">
    <view class="text-area">
      <view>
        <view> {{ userStore.token }}-{{ userStore.key }}当前位置信息：{{ locationAddress }} </view>
        <wd-button type="primary" @click="getLocationAuto">定位</wd-button>
        <wd-button type="primary" @click="openLocation">查看位置</wd-button>
        <wd-button type="primary" @click="searchHandle"> 搜索周边 </wd-button>
        <wd-button type="primary" @click="userStore.setToken(`${Date.now()}`)"> 设置token </wd-button>
      </view>

      <view />
      <wd-button @click="getLocation">地图上获取地址</wd-button>
      <wd-button type="primary" @click="addLocation">wx添加地址</wd-button>
      <wd-button type="success" @click="editLocation">wx编辑地址</wd-button>
      <view />
      <wd-upload
        ref="uploadRef"
        v-model:file-list="fileList1"
        accept="image"
        image-mode="aspectFill"
        :auto-upload="false"
        action="https://api-his.dev.jztdjk.cn/basic/admin-api/file/uploadFile"
        name="file"
        :form-data="{
          serverName: 'system',
          moduleName: 'user'
        }"
        :header="{
          Authorization: 'Bearer d4219f0c98ad45858dead947a3e0b2cb'
        }"
        @change="handleChange"
        @success="handleSuccess"
      >
        <wd-button>选择文件</wd-button>
      </wd-upload>
      <wd-button @click="onUploadClick">开始上传</wd-button>
      <wd-button @click="join('/subPackages/web/iframe')">百度外链</wd-button>
      <wd-button @click="join('/subPackages/web/rich-text')">显示自定义富文本内容</wd-button>
      <!-- <wd-button type="success" @click="join('/pages/map/index')"> 查看室内地图 </wd-button> -->
    </view>
  </view>
</template>

<style scoped lang="scss">
.content {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding-top: calc(env(safe-area-inset-top) + var(--status-bar-height));
}
</style>
